package com.luanye.enjoy.handler;

import com.luanye.enjoy.enums.ResultCode;
import com.luanye.enjoy.exception.APIException;
import com.luanye.enjoy.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(APIException.class)
    public RespBean apiExceptionHandler(APIException e){
        return RespBean.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public RespBean systemExceptionHandler(BindException e){
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        return new RespBean(ResultCode.VALIDATE_ERROR, error.getDefaultMessage());
    }

}
